/** sqlite数据库相关配置 */
import {
	OPT_SAVE,
	OPT_CALL,
	TAB_DISEASES, 
	TAB_DISEASEORDERLOG,
	TAB_DISEASEGRADE,
	TAB_DISEASECONTENT,
	TAB_LASTFILLINGRECORD,
	TAB_DISEASESTATUS,
	TAB_KEYWORDS,
	TAB_REPAIR,
	TAB_IMAGES,
	TAB_STATION,
	TAB_VIDEOS
} from './common.js'
import {doSave} from "../index.js"
//巡检的所有接口
import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
import {getPicture} from '@/api/doc.js' //获取图片
import { uploadFile, uploadVideoFile } from '@/utils/request'
import store from "@/store/index.js"
import {urlTobase64,localPathToBase64, saveFile, downLoadImage, downLoadVideo} from "@/utils/imageOperation.js"
// #ifdef APP-PLUS
import { DB } from "@/utils/offline/sqlite/dbinit.js";
import {fields as diseaseOrderLogFields} from "@/utils/offline/sqlite/init/diseaseOrderLog.js";
// #endif
/** 离线缓存的选项数据对应的离线文件路径（或文件名） */
const _map = new Map();
//本地持久化病害列表
_map.set('persisDiseaseOrderList', {
	type: OPT_SAVE,
	fields:async param => {
		const orderLog = param.diseaseOrderLogDto
		let docId
		if(orderLog) docId = orderLog.docId
		if(orderLog && docId) {
			const orderLogImgs = await downLoadImage(docId,false)
			for(let img of orderLogImgs) {
				// 缓存DiseaseOrderLogDto(当前Disease的上一个版本)对应的图片
				await doSave('persisDiseaseImageList',{...img, docInfoId:docId}, true)
			}
		}
		// 0417需求变动 开始
		let videoDocId
		if(orderLog) videoDocId = orderLog.videoDocId
		if(orderLog && videoDocId) {
			const orderLogImgs = await downLoadImage(videoDocId,false)
			for(let img of orderLogImgs) {
				// 缓存DiseaseOrderLogDto(当前Disease的上一个版本)对应的图片
				await doSave('persisDiseaseImageList',{...img, docInfoId:videoDocId}, true)
			}
		}
		// 0417需求变动 结束
		
		return {...param, _diseaseGradeId: param.diseaseGradeId}
	},
	exclude: ['diseaseOrderLogDto'], // 排除字段
	tableName: TAB_DISEASES,
	children: [
		{
			tableName: TAB_DISEASEORDERLOG,
			fields: parent => parent.diseaseOrderLogDto
		}
	]
})

//本地持久化图片信息
_map.set('persisDiseaseImageList', {
	type: OPT_SAVE,
	fields: param => param,
	tableName: TAB_IMAGES,
});


//本地持久化区间站点数据
_map.set('persisSectionSiteStateTree', {
	type: OPT_SAVE,
	fields: async pm => {
		console.log(pm, 'pm行doSave文件');
		const stations = []
		pm.list && pm.list.forEach(line => {
				line.list && line.list.forEach(category=>{
					category.list && category.list.forEach(station=>{
						stations.push({
							id: +station.id,
							name: station.name,
							mileage: station.mileage,
							type: station.type,
							amount: station.amount,
							categoryId: category.id,
							categoryName: category.name,
							lineId: line.id,
							lineName: line.name,
							pmId:pm.id,
							pmName:pm.name,
							branchLineName:line.branchLineName || ''
						})
					})
				})
			
		})
		// line.list && line.list.forEach()
		const fValues = stations.map(s=>`(${s.id}, '${s.name}','${s.mileage}','${s.type}',${s.amount||0},'${s.categoryId}','${s.categoryName}','${s.lineId}','${s.lineName}','${s.pmId}','${s.pmName}','${s.branchLineName}')`)
		await DB.execute(`insert or replace into ${TAB_STATION} 
		(id,name,mileage,type,amount,categoryId,categoryName,lineId,lineName,pmId,pmName,branchLineName)
		values ${fValues.join(',')}
		`)
		return {}
	}
})

_map.set(XUNJIAN.diseaseOrderSave, {
	type: OPT_SAVE,
	exclude: ['diseaseOrderLogDto', '_diseaseGradeId', '_orderType', '_from'], // 排除字段
	tableName: TAB_DISEASES,
	// 前置操作
	beforeActions: [
		{
			name: '是否已经提交过数据',
			// 必要性 boolean, 为false时,该后置操作不会被执行
			required: param => true,
			type: OPT_CALL,
			method: (param)=>{
				//code主要作用于上传数据到服务器时网络波动造成的请求失败或者请求不完整时对比服务端数据与本地数据的差异
				param.code = Math.random().toString().slice(2)
				param.submit = 0
				return param
			}
		},
		
		{
			name: '计算病害的变更状态',
			// 必要性 boolean, 为false时,该后置操作不会被执行
			required: param => param.orderType!=='add',
			type: OPT_CALL,
			method: async (param)=>{
				const {_orderType, followup:_followup, diseaseGradeId, _diseaseGradeId} = param
				const grades = await DB.select(`
					select id,code from diseaseGrade 
					where id in (${diseaseGradeId}, ${_diseaseGradeId})`)
				// const ranks = store.getters.dictMap['rank_class']
				const ranks = JSON.parse(uni.getStorageSync('rank_class'))
				const gradeName= {}
				grades.forEach(g => gradeName[g.id] = ranks.find(r=>r.code===g.code).name)
				let baseStatus, targetStatus,  followup // 基态 目标态 变更结果
				// 从历史未修复列表中进行变更, 取历史未修复转后状态作为基态
				baseStatus = gradeName[_diseaseGradeId]
				targetStatus = gradeName[diseaseGradeId]
				if(baseStatus === targetStatus) {
					followup = '无变化'
				} else {
					followup = `${baseStatus}转${targetStatus}`
				}
				param.followup = followup
				return param
			}
		},
		{
			name: '历史未修复---->变更  生成dto',
			// 必要性 boolean, 为false时,该后置操作不会被执行
			required: param => param.orderType ==='change' && param._from === 'history_not_repaired',
			type: OPT_CALL,
			method: async (param)=>{
				const V0 = await DB.select(`select * from diseases where id = ${param.id}`)
				const orderLog = {}
				diseaseOrderLogFields.forEach(f=>orderLog[f] = V0[0][f])
				orderLog.id = (0 - await DB.createId()),
				orderLog.diseaseOrderId= V0[0].id,
				orderLog.docId= V0[0].docId
				orderLog.videoDocId= V0[0].videoDocId
				
				const fNames = Object.keys(orderLog).filter(f=>orderLog[f])
				const fValues = fNames.map(f=>{
					let fv = orderLog[f]
					if(typeof fv === 'string') {
						fv = `'${fv}'`
					}else if(typeof fv === 'boolean') {
						fv = fv ? 1 : 0
					}
					return fv
				})
				let insertLogSql = `insert into diseaseOrderLog (${fNames.join(',')}) values (${fValues.join(',')})`
				// console.log(insertLogSql,'----insertLogSql---');
				await DB.execute(insertLogSql)
				
				return param
			}
		}
	],
	// 后置操作
	// afterAction: {
	// 	name: '病害变更后增加变更日志',
	// 	// 必要性 boolean, 为false时,该后置操作不会被执行
	// 	required: preParam => preParam.orderType!=='add',
	// 	// 操作类型: OPT_SAVE | OPT_DELETE
	// 	type: OPT_SAVE,
	// 	// 操作对应的配置项可以(即api)
	// 	api: XUNJIAN.cacheDiseaseOrderLog, 
	// 	// 该操作需要的参数对象
	// 	param: async (preParam, preId) => {
	// 		const lastVersion = preParam.version
	// 		const lastVersionDisease = (await DB.select(`
	// 			select * from diseases where id=${preParam.id} and version=${lastVersion}
	// 		`))[0]
	// 		const afterParam = {
	// 			...lastVersionDisease, 
	// 			diseaseOrderId: preId,
	// 		}
	// 		delete afterParam['id'] // 病害日志只有新增操纵, 所以需要删除id字段
	// 		return afterParam
	// 	}
	// }
});

//存储所有详情列表
_map.set(XUNJIAN.cacheDiseaseOrderLog, {
	type: OPT_SAVE,
	exclude: [
		'diseaseOrderLogDto', 
		'version', 
		'_diseaseGradeId',
		'_orderType'
	], // 排除字段
	dataFieldName: 'list',
	tableName: TAB_DISEASEORDERLOG,
	// fields: param => param,
})


//保存-病害等级(一级选项)
_map.set(XUNJIAN.cacheDiseaseGradeList, {
	type: OPT_SAVE,
	tableName: TAB_DISEASEGRADE,
	fields: param => param,
})

//保存-病害内容(二级)
_map.set(XUNJIAN.cacheDiseaseContent, {
	type: OPT_SAVE,
	tableName: TAB_DISEASECONTENT,
	fields: param => param,
})

//更新状态接口(保存上次填报记录)
_map.set(XUNJIAN.inspectLogUpdateState, {
	type: OPT_SAVE,
	tableName: TAB_LASTFILLINGRECORD,
	fields: param => param,
	// 前置操作
	beforeActions: [
		{
			name: '区间/站点点击开始或者结束按钮后变更数据库表区间/站点对应的状态',
			required: param => true,
			type: OPT_CALL,
			method: async (param)=>{
				await DB.execute(`update stations 
				set type = '${param.inspectState}' 
				where id = ${param.lineSiteSectionId}`)
				return param
			}
		}
	],
	
})


//本地持久化病害关键字列表
_map.set(XUNJIAN.diseaseKeywordsList, {
	type: OPT_SAVE,
	tableName: TAB_KEYWORDS, 
	fields: param => param,
})
//本地持久化病害现状列表
_map.set(XUNJIAN.diseaseStatusList, {
	type: OPT_SAVE,
	tableName: TAB_DISEASESTATUS,
	fields: param => param,
})

//本地持久化修复措施列表
_map.set(XUNJIAN.diseaseMaterialList, {
	type: OPT_SAVE,
	tableName: TAB_REPAIR,
	fields: param => param,
})


//本地持久化上传的图片
_map.set(uploadFile, {
	type: OPT_SAVE,
	tableName: TAB_IMAGES,
	exclude:['base64Images'],   
	fields: async param => {
		console.log(param,'172行');
		let base64Images = []
		if(!param.formData.docId){
		  param.formData.docId = (0 - await DB.createId())
		}
		for (let item of param.files) {
			base64Images.push({
				id:(0 - await DB.createId()),
				url:(await saveFile(item.uri)),
				dataList:param.formData.dataList,
				projectId:param.formData.projectId,
				docInfoId:param.formData.docId
			})
		}
		param.base64Images = base64Images
		console.log(base64Images,'base64Images');
		return {base64Images}
	},
	children: [
		{
			tableName: TAB_IMAGES,
			fields: parent => {
				return parent.base64Images
			}
		}
	],
	resultMapping: (data,param) => ({id: param.formData.docId})
})

export const apiDataMapping = _map;
